/*
============================================================================
 Name        : $(GuiBasename)AppUi.cpp
 Author      : $(Author)
 Version     :
 Copyright   : $(Copyright)
 Description : 
============================================================================
*/

// INCLUDE FILES
#include <avkon.hrh>
#include <aknmessagequerydialog.h>
#include <aknnotewrappers.h>
#include <stringloader.h>
#include <$(GuiBasename).rsg>
#include <f32file.h>
#include <s32file.h>
#include <bautils.h>
#include <charconv.h>
#include <hlplch.h>

#include "$(GuiBasename).pan"
#include "$(GuiBasename)Application.h"
#include "$(GuiBasename)AppUi.h"
#include "$(GuiBasename)AppView.h"
#include "$(GuiBasename).hrh"

#include "$(GuiBasename)_$(uid).hlp.hrh"

// ============================ MEMBER FUNCTIONS ===============================


// -----------------------------------------------------------------------------
// C$(GuiBasename)AppUi::ConstructL()
// Symbian 2nd phase constructor can leave.
// -----------------------------------------------------------------------------
//
void C$(GuiBasename)AppUi::ConstructL()
	{
	// Initialise app UI with standard value.
	BaseConstructL();
	
	iEngine = C$(LibBasename2)::NewL();

	// Create view object
	iAppView = C$(GuiBasename)AppView::NewL( ClientRect() );
	
	PrivacyStatementL();
	}
// -----------------------------------------------------------------------------
// C$(GuiBasename)AppUi::C$(GuiBasename)AppUi()
// C++ default constructor can NOT contain any code, that might leave.
// -----------------------------------------------------------------------------
//
C$(GuiBasename)AppUi::C$(GuiBasename)AppUi()
	{
	// No implementation required
	}

// -----------------------------------------------------------------------------
// C$(GuiBasename)AppUi::~C$(GuiBasename)AppUi()
// Destructor.
// -----------------------------------------------------------------------------
//
C$(GuiBasename)AppUi::~C$(GuiBasename)AppUi()
	{
	if ( iAppView )
		{
		delete iAppView;
		iAppView = NULL;
		}
	delete iEngine;
	}

// -----------------------------------------------------------------------------
// C$(GuiBasename)AppUi::HandleCommandL()
// Takes care of command handling.
// -----------------------------------------------------------------------------
//
void C$(GuiBasename)AppUi::HandleCommandL( TInt aCommand )
	{
	switch( aCommand )
		{
		case EEikCmdExit:
		case EAknSoftkeyExit:
			Exit();
			break;
		case E$(GuiBasename)Command1:
			{			
			// Load a string from the resource file and display it
			HBufC* textResource = StringLoader::LoadLC( R_HEWB_COMMAND1_TEXT );
			CAknInformationNote* informationNote = new ( ELeave ) CAknInformationNote;
			// Show the information Note with textResource loaded with StringLoader.
			informationNote->ExecuteLD( *textResource);
			// Pop HBuf from CleanUpStack and Destroy it.
			CleanupStack::PopAndDestroy( textResource );
			}
			break;
		case E$(GuiBasename)Command2:
			{
			// Use the engine DLL
			TInt ch;
			for(ch = 'A'; ch <= 'O'; ch++)
				{
				iEngine->ExampleFuncAddCharL(ch);
				}
			// Show the information Note with text from the engine
			CAknInformationNote* informationNote = new (ELeave) CAknInformationNote;
			informationNote->ExecuteLD(iEngine->ExampleFuncString());
			iEngine->ExampleFuncClearBuffer();
			}
			break;
		case EHelp:
			{
			CArrayFix<TCoeHelpContext>* buf = CCoeAppUi::AppHelpContextL();
			HlpLauncher::LaunchHelpApplicationL(iEikonEnv->WsSession(), buf);
			}
			break;
		case EAbout:
			{
			CAknMessageQueryDialog* dlg = new (ELeave)CAknMessageQueryDialog(); 
			dlg->PrepareLC(R_ABOUT_QUERY_DIALOG);
			HBufC* title = iEikonEnv->AllocReadResourceLC(R_ABOUT_DIALOG_TITLE);
			dlg->QueryHeading()->SetTextL(*title);
			CleanupStack::PopAndDestroy(); //title
			HBufC* msg = iEikonEnv->AllocReadResourceLC(R_ABOUT_DIALOG_TEXT);
			dlg->SetMessageTextL(*msg);
			CleanupStack::PopAndDestroy(); //msg
			dlg->RunLD(); 
			}
			break;
		default:
			Panic( E$(GuiBasename)Ui );
			break;
		}
	}

// -----------------------------------------------------------------------------
//  Called by the framework when the application status pane
//  size is changed.  Passes the new client rectangle to the
//  AppView
// -----------------------------------------------------------------------------
//
void C$(GuiBasename)AppUi::HandleStatusPaneSizeChange()
	{
	iAppView->SetRect( ClientRect() );
	}

CArrayFix<TCoeHelpContext>* C$(GuiBasename)AppUi::HelpContextL() const
	{
	// Note: help will not work if the application uid3 is not in the
	// protected range.  The default uid3 range for projects created
	// from this template (0xE0000000 - 0xEFFFFFFF) are not in the protected range so they
	// can be self signed and installed on the device during testing.
	// Once you get your official uid3 from Symbian Ltd. and find/replace
	// all occurrences of uid3 in your project, the context help will
	// work.
	CArrayFixFlat<TCoeHelpContext>* ctxs = new(ELeave)CArrayFixFlat<TCoeHelpContext>(1);
	CleanupStack::PushL(ctxs);
	ctxs->AppendL(TCoeHelpContext(KUid$(GuiBasename)App, KGeneral_Information));
	CleanupStack::Pop(ctxs);
	return ctxs;
	}
	
void C$(GuiBasename)AppUi::PrivacyStatementL() 
	{
	// Note: to see privacy statement in emulator, copy
	// PrivacyStatement.txt from group/ directory to 
	// %EPOCROOT%\Epoc32\release\winscw\udeb\z\private\$(uidHexValue)\
	// Also note that on emulator you can't modify files on Z: drive,
	// so even if you answer Yes to privacy statement, it will popup
	// dialog every time you launch application. But on device it will work
	// as expected.
	HBufC * fileName = StringLoader::LoadLC(R_PRIVACY_STATEMENT_FILENAME);
	RFs &fs= iCoeEnv->FsSession();
	
	// Make full path to privacy statement
	TFileName fullFileName;
	TFileName privatePath;
	fs.PrivatePath(privatePath);
	TParse parser;
	TFileName processFileName(RProcess().FileName());
	User::LeaveIfError(parser.Set(*fileName, &privatePath, &processFileName));
	fullFileName = parser.FullName();
	CleanupStack::PopAndDestroy(fileName);
	
	if(BaflUtils::FileExists(fs, fullFileName)) 
		{
		RBuf text(C$(GuiBasename)AppUi::ReadUnicodeFileL(fs, fullFileName));
		CleanupClosePushL(text);
		CAknMessageQueryDialog *dialog = CAknMessageQueryDialog::NewL(text);
		if(dialog->ExecuteLD(R_PRIVSTMT_DIALOG) == EAknSoftkeyYes) 
			{
			BaflUtils::DeleteFile(fs, fullFileName);
			}
		CleanupStack::PopAndDestroy(&text);
		}
	}

HBufC * C$(GuiBasename)AppUi::ReadUnicodeFileL(RFs& aFs, const TDesC& aFileName)
	{
	RFile file;
	User::LeaveIfError(file.Open(aFs, aFileName, EFileShareReadersOnly | EFileStreamText | EFileRead));
	CleanupClosePushL(file);

	TInt size;
	User::LeaveIfError(file.Size(size));

	RBuf8 tmp;
	tmp.CreateL(size);
	CleanupClosePushL(tmp);
	User::LeaveIfError(file.Read(tmp));

	CCnvCharacterSetConverter * converter = CCnvCharacterSetConverter::NewLC();
	converter->PrepareToConvertToOrFromL(KCharacterSetIdentifierUtf8, aFs);

	HBufC *text = HBufC::NewL(size);

	TInt state = CCnvCharacterSetConverter::KStateDefault;
	TPtrC8 remainderOfForeignText(tmp);
	for(;;)
		{
		TPtr textPtr(text->Des());
		TInt retValue = converter->ConvertToUnicode(textPtr, remainderOfForeignText, state);
		if(retValue == CCnvCharacterSetConverter::EErrorIllFormedInput)
			User::Leave(KErrCorrupt);
		else if(retValue < 0)
			User::Leave(KErrGeneral);
		
		if(retValue == 0)
			break;
			
		remainderOfForeignText.Set(remainderOfForeignText.Right(retValue));
		}	
	
	CleanupStack::PopAndDestroy(converter);
	CleanupStack::PopAndDestroy(2);
	return text;
	}
	
// End of File